package cn.yangphere.web.action.product;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.yangphere.bean.AnnotationUtils;
import cn.yangphere.bean.PageView;
import cn.yangphere.bean.QueryResult;
import cn.yangphere.bean.product.ProductType;
import cn.yangphere.service.product.ProductTypeService;
import cn.yangphere.web.formbean.product.ProductTypeForm;

@Controller("/control/product/type/list")
@Scope("prototype")
public class ProductTypeAction extends Action {

	@Resource(name = "productTypeServiceBean")
	private ProductTypeService productTypeService;

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ProductTypeForm formbean = (ProductTypeForm) form;
		
		StringBuffer jpql = new StringBuffer("o.visible=?1");
		List<Object> params = new ArrayList<Object>();
		params.add(true);
		
		if("true".equals(formbean.getQuery())){
			if(StringUtils.isNotEmpty(formbean.getName())){
				jpql.append(" and o.name like ?" + (params.size()+1));
				params.add("%"+formbean.getName()+"%");
			}
		}else{
			if(formbean.getParentId()!=null && formbean.getParentId()>0){
				jpql.append(" and o.parent.typeid=?" + (params.size()+1));
				params.add(formbean.getParentId());
			}else{
				jpql.append(" and o.parent is null ");
			}
		}
		
		PageView<ProductType> pageView = new PageView<ProductType>(12, formbean.getPage());
		
		LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
		orderBy.put("typeid", "desc");
		QueryResult<ProductType> qr = productTypeService.getScrollData(ProductType.class, 
				pageView.getFirstIndex(), pageView.getMaxResult(),
				jpql.toString(), params.toArray(), orderBy);
		pageView.setQueryResult(qr);
		
		request.setAttribute("pageView", pageView);		
		return mapping.findForward("list");
	}
}
